package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;
import cn.com.kh.signUtil;
import cn.com.kh.AESUtil;

import org.json.JSONArray;
import org.json.JSONException;

import org.json.JSONObject;
//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.parser.Feature;
/**
 *
 * @Title: ApiBPOverview
 * @Description:深圳宝安排水小程序查询案件总览--外部接口
 * @author: chieh
 * @date 2020-11-11 21:28:00
 *
 */
public class ApiBPOverview implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(ApiBPOverview.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
		
		log.debug("-------------------------start apiBPOverview 开始-----------------");
		
        long startTime = System.currentTimeMillis();
        String reJson = null;
        long endTime = 0;
		
		response.setContentType("application/json;charset=utf-8");
		
		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}
		
        try {
			
			// 调用处理信息
			//JSONObject inObject = JSONObject.parseObject(inData, Feature.OrderedField);
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());
			
			//openid 排序问题
			JSONArray jsonArraytemp = new JSONArray(inObject.get("data").toString());
			log.debug("jsonArraytemp: " + jsonArraytemp);
			
			JSONObject dataObjecttemp = jsonArraytemp.getJSONObject(0);
			log.debug(dataObjecttemp);
			String openidtemp = GetJV(dataObjecttemp, "openid");
			log.debug("openid:"+openidtemp);
			
			String replaceString ="[{\"openid\":\""+openidtemp+"\"}]";
			log.debug("replaceString:"+replaceString);
			
			//鉴权加密处理--验证密码
			JSONObject checkJson = signUtil.CheckSign(inObject,replaceString);
			log.debug("checkJson: " + checkJson);

			if (checkJson != null) {
				log.debug("[签名校验异常-返回信息]:" + checkJson);
				endTime = System.currentTimeMillis();
				reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败([签名校验异常-返回信息]:"+signUtil.jsonObjectToMap(checkJson)+"),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
				return reJson;
			} else {
				log.debug("[签名校验成功]");
				// 校验成功
				//todo 业务逻辑
			}
			//data获取参数openid
			JSONArray jsonArray = new JSONArray(inObject.get("data").toString());
			log.debug("jsonArray: " + jsonArray);
			def openid= jsonArray.getJSONObject(0).get("openid");
			
			log.debug("解析信息-openid：" + openid);
						
            if (openid == null||openid == ""||openid=="undefined") {
                endTime = System.currentTimeMillis();
                reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(openid必填字段;),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                return reJson;
            }
			def listcountresult =eliteBean.chaxun_sql("SELECT isnull(count(*),'') as reportedcount,isnull(sum(case when curstep_id_map='KNGZL4' and objectivestatus='OPEN' then 1 else 0 end),'') as handlecount,isnull(sum(case when objectivestatus='CLOSE'  then 1 else 0 end),'') as finishcount,isnull(sum(case when objectivestatus='OPEN'  then 1 else 0 end),'') as nofinishcount FROM objective o LEFT JOIN TABCCONSULTWORKORDER t  on t.RELATION_ID=objective_guid LEFT JOIN customer c on o.customer_guid =c.customer_guid WHERE t.business_source = '3E98AF' AND c.wechatid = '"+openid+"'","dataSource");
			def reportedcount = 0;
			def handlecount = 0;
			def finishcount = 0;
			def nofinishcount = 0;
			def count=listcountresult.size();
			if(count > 0) {
				reportedcount = listcountresult.get(0).get("reportedcount");
				handlecount = listcountresult.get(0).get("handlecount");
				finishcount = listcountresult.get(0).get("finishcount");
				nofinishcount = listcountresult.get(0).get("nofinishcount");
			}
			JSONArray jsonArray1 = new JSONArray();
			// json对象
			JSONObject json = new JSONObject();
			if(reportedcount==null) {
				reportedcount=0;
			}
			if(handlecount==null) {
				handlecount=0;
			}
			if(finishcount==null) {
				finishcount=0;
			}
			if(nofinishcount==null) {
				nofinishcount=0;
			}
			
			json.put("applied",reportedcount);
			json.put("handle",handlecount);
			json.put("complete",finishcount);
			json.put("nocomplete",nofinishcount);
			
			jsonArray1.put(json);
						
			endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"获取工单总览接口调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":"+jsonArray1.toString()+"}";
			
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"获取工单总览接口调用处理失败(" + e.getMessage() + ")\",\"data\":[]}";

        }
        return reJson;

    }
	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}
}